package elems;

import common.ParseException;
import common.Strings;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Var extends ClassElem {
    private String command;
    private String comment;

    private Var(Clazz parent, String command, String comment) {
        super(parent);
        this.command = command;
        this.comment = comment;
    }

    public void print(int shift) {
        System.out.println(Strings.getSpaceShift(shift) + command + " /* VAR " + comment + " */");
    }

    public static boolean is(int lineNum, String text) throws ParseException {
        ArrayList<String> strs = Strings.split(lineNum, text, "//", true, false);
        String tStr = strs.get(0).trim();
        if (tStr.length() == 0 || !tStr.contains(":"))
            return false;

        Pattern pattern = Pattern.compile("^@[A-Za-z0-9_]+ *:.*$");
        Matcher matcher = pattern.matcher(tStr);

        return matcher.find();
    }

    public static Var get(Clazz parent, int lineNum, String text) throws ParseException {
        if (!is(lineNum, text))
            return null;
        ArrayList<String> tStrs = Strings.split(lineNum, text, "//", true, false);
        return new Var(parent, tStrs.get(0).trim(), (tStrs.size() > 1) ? tStrs.get(1).trim() : "");
    }
}
